require 'net/http'

class BluePages < ActiveRecord::Base

  def self.get_user_info(username)
    if username == ""
      return false 
    end

    retry_count = 0

    blue_pages_url = 'bluepages.ibm.com'
    user_search_path = '/BpHttpApisv3/wsapi?byInternetAddr='

    begin
      @user_info = Net::HTTP.get(blue_pages_url, user_search_path + username)
    rescue SocketError
      return false
    end

    return @user_info
  end

  def self.get_first_last_name(username)
    if !@user_info
      return false
    else
      return BluePages.get_user_info(username).scan(/NAME: ([\w\s]*), ([\w]*)/)[0].reverse
    end
  end

  def self.get_uid(username)
    # regex to match pattern "CNUM: 1234ABCD" and extract 1234ABCD
    user_info = BluePages.get_user_info(username)
    uid_array = /CNUM: ([\w\d]*)/.match(user_info)
    if uid_array.nil? || uid_array.size < 2
      return false
    end
    return uid_array[1]
  end
end
